<?php
    class Database{
        const HOST="47.93.12.165";
        const USERNAME="root";
        const PASSWORD="chuixue";
        const DB="postServer";
        
        
        private function getConnection(){
            $username = self::USERNAME;
            $password = self::PASSWORD;
            $host = self::HOST;
            $db = self::DB;
            $connection = new PDO("mysql:dbname=$db;host=$host", $username, $password);
            $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $connection->query("SET NAMES utf8");
            return $connection;
        }
        
		public function Run($sql, $args=array()){
		    try{
    		    $connection = $this->getConnection();
        		$stmt = $connection->prepare($sql);
        		$rst = $stmt->execute($args);
        		$id = $connection->lastInsertId();
		    }catch(Exception $e){
		        echo $e;
		        $id = -1;
		    }
			return $id;
        }
        
        public function RunSqls($sqls, $args=array()){
			$connection = $this->getConnection();
            $rsts = array();
            $ids = array();
            try{
                $connection->beginTransaction();
                for ($i = 0; $i < count($sqls); $i++){ 
                    $stmt = $connection->prepare($sqls[$i]);
			        $rsts[$i] = $stmt->execute($args[$i]);
                    $ids[$i] = $connection->lastInsertId();
                }
                $connection->commit();
            }catch(Exception $e){
                $connection->rollBack();
                return null;
            }
			return array($ids, $rsts);
        }
        
		
        public function Select($sql, $args=array(), &$conn=null){
            $connection = $this->getConnection();
            $stmt = $connection->prepare($sql);
            $stmt->execute($args);
            $conn = $connection;
            return $stmt;
        }
        public function SubSelect($connection, $sql, $args=array()){
            $stmt = $connection->prepare($sql);
            $stmt->execute($args);
            return $stmt->fetchAll(PDO::FETCH_ASSOC); ;
        }
        
        public function SelectEx($sql, $args=Array()){
            return $this->Select($sql, $args)->fetchAll(PDO::FETCH_ASSOC); 
        }
        
    }
	
    $obj = PDO::FETCH_OBJ;
	
	/*
	include "database.php";
    $db = new Database();
	$rst = $db->Run("insert into article_temp set createTime=?", array(date("Y-m-d H:i:s")));
    //$rst = $db->Run("insert into article_temp set createTime='2017-07-03 19:30:38'");
	echo $rst
	$rst = $db->Select("");
    while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
        print_r($row);
    }  
	*/
	
	
?>